package world.xuewei.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import world.xuewei.model.entity.R;
import world.xuewei.model.entity.ShopNotice;
import world.xuewei.service.ShopNoticeService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/notice")
@Slf4j
public class ShopNoticeController {

    /**
     * 服务对象
     */
    @Resource
    private ShopNoticeService shopNoticeService;

    // 获取店铺公告（商家端）
    @GetMapping("/getAllShopNotice")
    public R getAllShopNotice(HttpServletRequest request) {
        String userIdStr = (String) request.getAttribute("userId");
        if (userIdStr == null) {
            return R.error().message("用户未登录 or 携带token请求");
        }
        Long userId = Long.parseLong(userIdStr);
        List<ShopNotice> shopNoticeList = shopNoticeService.getAllShopNoticeList(userId);
        return R.ok().data(shopNoticeList);
    }

    // 获取店铺公告（用户端）
    @GetMapping
    public R getShopNotice(@RequestParam("merchant_id") Long merchant_id) {
        List<ShopNotice> shopNotices = shopNoticeService.getShopNoticeList(merchant_id);
        return R.ok().data(shopNotices);
    }

    // 添加商家公告
    @PostMapping
    public R addShopNotice(@RequestBody ShopNotice shopNotice) {
        System.out.println(shopNotice);
        int i = shopNoticeService.addShopNotice(shopNotice);
        if (i > 0) {
            return R.ok().message("添加成功");
        } else {
            return R.error().message("添加失败");
        }
    }

    // 修改商家公告
    @PutMapping
    public R updateShopNotice(@RequestBody ShopNotice shopNotice) {
        int i = shopNoticeService.updateShopNotice(shopNotice);
        if (i > 0) {
            return R.ok().message("修改成功");
        } else {
            return R.ok().message("修改失败");
        }

    }

    // 删除
    @DeleteMapping("{id}")
    public R deleteShopNotice(@PathVariable(value = "id") Long id) {
        int i = shopNoticeService.deleteShopNotice(id);
        if (i > 0) {
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }
}
